/**
 * Created by leo on 1/26.
 */
(function (window, $) {
    "use strict";
    if (!$) {
        throw "高度自适应需要jQuery支持!";
    }
    $(function () {
        var parent = window.parent, top = window.top, document = window.document;
        // 高度自适应, 通过url参数传递tab序号
        if (window != top && parent == top) {
            parent.postMessage("IFRAME_LOADED?title=" + encodeURIComponent(document.title) + "&url=" + encodeURIComponent(location.href), '*');
            var oldHeight = 0, active = true, syncHeight, timeoutId;
            (syncHeight = function () { // 触发iframe高度同步
                if (document.body) {
                    var height = $(document.body).outerHeight();
                    if (!document.body.style.height) {
                        height += 20;
                    }
                    if (oldHeight != height && Math.abs(height - oldHeight - 20) <= 2) {
                        parent.postMessage("IFRAME_RESIZE?height=" + height, '*');
                        oldHeight = height;
                    }
                }
                if (active) {
                    timeoutId = setTimeout(syncHeight, 100);
                }
            })();
            var AddMessageListener = function (callback) {
                return window.attachEvent ? window.attachEvent('onmessage', callback) : window.addEventListener('message', callback);
            };
            AddMessageListener(function (e) {
                // 监听TAB切换消息，以便决定是否要执行高度同步逻辑
                var message = e.data;
                if (e.source == top && typeof message == "string" && message.indexOf('TAB_SWITCH?') == 0) {
                    clearTimeout(timeoutId);
                    active = message.indexOf('ON') > 0;
                    if (active) { // 从OFF切换到ON状态，启动高度同步任务
                        syncHeight();
                    }
                }
            });

            // 提供老版本portal中的api支持
            // addTab(tabName, url);
            // addTab(tabId, tabName, url);
            // removeTab(tabId);
            // refreshPanel(tabId);
            // autoHeight(panelId,iframe_height);
            window.addTab = function addTab() {
                var args = arguments, tabName = args[0], url = args[1];
                if (args.length == 3) {
                    tabName = args[1];
                    url = args[2];
                }
                top.postMessage('TAB_ADD?name=' + encodeURIComponent(tabName) + '&url=' + encodeURIComponent(url), '*');
            };
            var closeFlag = false;
            window.removeTab = function removeTab() { // 只允许当前页面的TAB
                if (closeFlag === false) {
                    closeFlag = true;
                    top.postMessage('TAB_REMOVE', '*');
                    window.close();
                }
            };
            //window.refreshPanel = window.autoHeight = function() {};
        }
    });
}(window, jQuery));
